import { wsUrl } from "@/common/baseconfig.js"
import cookie from '@/utils/auth.js'



function Ws() {
	//是否已经连接上ws
	this.isOpenSocket = false,
	//心跳间隔，单位毫秒
	this.heartBeatDelay = 10000,
	this.heartBeatInterval = null,
	//心跳时发送的消息文本
	this.heartBeatText = "Ping",
	//最大重连次数
	this.reconnectTimes = 10,
	this.reconnectInterval = null,
	//重连间隔，单位毫秒
	this.reconnectDelay = 3000,
	this.socketTask = null,
	//这个参数是防止重连失败之后onClose方法会重复执行reconnect方法，导致重连定时器出问题
	//连接并打开之后可重连，且只执行重连方法一次
	this.canReconnect = false,
	//封装的对象，最后以模块化向外暴露，
	//init方法 初始化socketTask对象
	//completeClose方法 完全将socketTask关闭（不重连）
	//其他关于socketTask的方法与uniapp的socketTask api一致
	this.ws = {
		socketTask: null,
		init: null,
		send: null,
		completeClose: null
	}
}
Ws.prototype = {
	constructor: Ws,
	init() {
		// 两个参数：发送不同的标识&处理接收消息
		try {
			if (!cookie.get('Token')) return
			this.socketTask = uni.connectSocket({
				url: wsUrl + '/websocketConnet?Token=' + cookie.get('Token') || ' ',
				fail(e) {
					console.log(e)
				},
				complete: (e) => {}
			})
			this.socketTask.onOpen((res) => {
				console.log("ws连接成功")
				clearInterval(this.heartBeatInterval)
				clearInterval(this.reconnectInterval)
				this.isOpenSocket = true
				this.canReconnect = true
				this.send(JSON.stringify(this.heartBeatText));
				//开启心跳机制
				this.heartBeat()
			})
			this.socketTask.onMessage((res) => {
				//自定义处理onMessage方法
				// console.log(res)
				this.onWsMessage(res)
			})
			this.socketTask.onClose(() => {
				if (this.isOpenSocket) {
					console.log("ws与服务器断开")
				} else {
					console.log("连接失败")
				}
				this.isOpenSocket = false
				if (this.canReconnect) {
					this.reconnect()
					this.canReconnect = false
				}
			})
			this.ws.socketTask = this.socketTask
		} catch (e) {
			return
			//TODO handle the exception
		}

	},
	heartBeat() {
		this.heartBeatInterval = setInterval(() => {
			this.send(JSON.stringify(this.heartBeatText));
		}, this.heartBeatDelay)
	},
	onWsMessage({ data }) {
		// 处理接收消息
		const jsonStr = data;
		if (!data) return
		try {
			const msg = JSON.parse(data);
			Chat.manage(msg)
		} catch (e) {
			console.log('消息发送=====>', e)
			//TODO handle the exception
		}
		// console.log('onWsMessage接收到服务器的数据: ', jsonStr)
	},
	send(value) {
		return new Promise((resolve, reject) => {
			this.ws.socketTask.send({
				data: value,
				async success() {
					resolve(true)
					// console.log("消息标识发送成功", value)
				},
				fail() {
					reject(false)
				}
			})
		});
	},
	reconnect() {
		//停止发送心跳
		clearInterval(this.heartBeatInterval)
		//如果不是人为关闭的话，进行重连
		if (!this.isOpenSocket) {
			let count = 0;
			console.log("正在尝试重连")
			this.init();
			this.reconnectInterval = setInterval(() => {
				this.init();
				count++
				//重连一定次数后就不再重连
				if (count >= this.reconnectTimes) {
					clearInterval(this.reconnectInterval)
					console.log("网络异常或服务器错误")
				}
			}, this.reconnectDelay)
		}
	},
	completeClose() {
		//先将心跳与重连的定时器清除
		clearInterval(this.heartBeatInterval)
		clearInterval(this.reconnectInterval)
		this.canReconnect = false;
		if(this.socketTask){
			this.socketTask.close();
		}
	}
}


export default new Ws();
